package com.eirikb.client;

import com.eirikb.shared.ServiceAsync;
import com.eirikb.shared.Service;
import com.eirikb.client.ui.Chat;
import com.eirikb.client.ui.Login;
import com.eirikb.shared.events.Event;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.RootPanel;

/**
 *
 * @author eirikb
 */
public class Client implements EntryPoint {

    private String nick;
    private Chat chat;
    private Login login;
    private Client client;
    private Timer timer;
    private final int REFRESHRATE = 2;
    private boolean loggedIn;

    public Client() {
    }

    public void onModuleLoad() {
        client = this;
        chat = new Chat(this);
        login = new Login(this);
        RootPanel.get().add(login);
    }

    public void showChat() {
        loggedIn = true;
        RootPanel.get().clear();
        RootPanel.get().add(chat);
        loop(true);
    }

    public String getNick() {
        return nick;
    }

    public void setNick(String nick) {
        this.nick = nick;
    }

    public Chat getChat() {
        return chat;
    }

    public Login getLogin() {
        return login;
    }

    public boolean isLoggedIn() {
        return loggedIn;
    }

    public void loop(boolean loop) {
        if (loop) {
            timer = new Timer() {

                public void run() {
                    client.checkUpdates();
                }
            };
            timer.scheduleRepeating(REFRESHRATE * 1000);
        } else {
            timer.cancel();
        }
    }

    public void checkUpdates() {
        final AsyncCallback<Event[]> callback = new AsyncCallback<Event[]>() {

            public void onSuccess(Event[] events) {
                for (Event event : events) {
                    event.execute(client);
                }
            }

            public void onFailure(Throwable caught) {
                client.loop(false);
                Window.alert(caught.toString());
            }
        };
        Client.getService().checkUpdates(nick, callback);
    }

    public static ServiceAsync getService() {
        ServiceAsync service = (ServiceAsync) GWT.create(Service.class);
        ServiceDefTarget endpoint = (ServiceDefTarget) service;
        String moduleRelativeURL = GWT.getModuleBaseURL() + "service";
        endpoint.setServiceEntryPoint(moduleRelativeURL);
        return service;
    }
}
